#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @TIME : 2020/9/13 15:59
# @AUTHOR : fengzhilaoling
from django.utils.deprecation import MiddlewareMixin
from django.core.cache import cache
from time import time
from django.http import HttpResponse


class info(MiddlewareMixin):

    def process_request(self, request):
        """
        通过频率进行反爬设置
        一分钟刷新次数不能超过10次，超过10次15秒后才能重试
        一分钟内超过30次，IP被封1天
        """
        current_path = request.path
        ip = request.META.get('REMOTE_ADDR')
        blacklist = cache.get('blacklist', [])
        if ip in cache.get('blacklist', []):
            print(blacklist)
            return HttpResponse('过1天在来！')
        result = cache.get(str(current_path + ip), [])
        while result and time() - result[-1] > 60:
            result.pop()
        result.insert(0, time())
        cache.set(str(current_path + ip), result, 60)
        if len(result) > 30:
            blacklist.append(ip)
            cache.set('blacklist', blacklist, 60 * 60 * 60 * 24)
            return HttpResponse('过1天在来！')
        elif len(result) > 10:
            print(len(result))
            return HttpResponse('15秒后再试！')

    def process_exception(self, request, response):
        return HttpResponse('出现异常')
